/**
 * Created on 20.07.2012
 */
package com.example.some.v3;

/**
 * @author Ciprian Mihalache
 *
 */
public class MathUtils {

	/**
	 * Utility method for computing the sum of two numbers
	 * 
	 * @param a
	 *            the first number
	 * @param b
	 *            the second number
	 * @return the sum of the provided numbers
	 * @throws ArithmeticException
	 *             in case the sum can not be represented as an int
	 */
	public static int sum(int a, int b) throws ArithmeticException {
		if (a > b) {
			return orderedNumbersSum(b, a);
		}
		return orderedNumbersSum(a, b);
	}

	private static int orderedNumbersSum(int a, int b) {
		if (a > 0) {
			return orderedPositiveNumbersSum(a, b);
		} else {
			if (b >= 0) {
				return a + b;
			} else {
				return orderedNegativeNumbersSum(a, b);
			}
		}
	}

	private static int orderedPositiveNumbersSum(int a, int b) {
		if (a <= Integer.MAX_VALUE - b) {
			return a + b;
		} else {
			throw new ArithmeticException("Overflow while computing the sum");
		}
	}

	private static int orderedNegativeNumbersSum(int a, int b) {
		if (a >= Integer.MIN_VALUE - b) {
			return a + b;
		} else {
			throw new ArithmeticException("Overflow while computing the sum");
		}
	}
}
